<template>
    <router-view/>
</template>

<script setup lang="ts">
import {useRoute} from "vue-router";
const route = useRoute()
import {onMounted,ref} from "vue";
import {userStore} from "./store/user.ts";
import router from "./router";
import ACCESS_ENUM from "./access/accessEnum.ts";
import checkAccess from "./access/checkAccess.ts";


onMounted(async () => {
    const store = userStore();
    router.beforeEach(async (to, from, next) => {
        console.log("登陆用户信息:", store.loginUser);
        let loginUser = store.loginUser;
        // // 如果之前没登陆过，自动登录
        if (!loginUser || !loginUser.userRole) {
            // 加 await 是为了等用户登录成功之后，再执行后续的代码
            await store.updateLoginUser();
            loginUser = store.loginUser;
        }
        const needAccess = (to.meta?.access as string) ?? ACCESS_ENUM.NOT_LOGIN;
        // 要跳转的页面必须要登陆
        if (needAccess !== ACCESS_ENUM.NOT_LOGIN) {
            // 如果没登陆，跳转到登录页面
            if (!loginUser || loginUser.userRole == ACCESS_ENUM.NOT_LOGIN) {
                await alert("请先登录")
                await next(`/user/login`);
                return;
            }
            // 如果已经登陆了，但是权限不足，那么跳转到无权限页面
            if (!checkAccess(loginUser, needAccess)) {
                next("/noAuth");
                return;
            }
        }
        next();
    });


})

</script>


<style scoped>
html,body,div,span,h1,h2,h3,h4,h5,h6,ul,ol,li,p {
    margin: 0;
    padding: 0;
}
html,body,#app {
    width: 100%;
    height: 100%;
    font-family: "微软雅黑",serif;
}
ul,ol {
    list-style: none;
}
a {
    text-decoration: none
}
</style>
